package org.imis181.moqilintong.model;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.util.Objects;

/**
 * 根据运算符生成运算器
 * @author moqilintong
 */
public class OperationFactory {
    /**
     * Do not let anyone instantiate this class
     */
    private OperationFactory() {}

    public static Calculable01 produceCalculable(String opcode) {
        Calculable01 calculable = null;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setValidating(false);
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(OperationFactory.class.getClassLoader().getResourceAsStream("operations.xml"));
            NodeList classList = document.getElementsByTagName("class");
            for (int i = 0; i < classList.getLength(); i++) {
                Node parentNode = classList.item(i).getParentNode();
                NamedNodeMap attributes = parentNode.getAttributes();
                if (attributes.getNamedItem("id").getNodeValue().equalsIgnoreCase(opcode)) {
                    calculable = (Calculable01)Class.forName(classList.item(i).getTextContent()).newInstance();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (Objects.isNull(calculable)) {
            throw new IllegalArgumentException(String.format("不能识别的运算符： %s", opcode));
        }
        return calculable;
    }
}
